import { ChangeEvent, useState } from 'react'
import { alpha, styled } from '@mui/material'
import SearchIcon from '@mui/icons-material/Search'
import InputBase from '@mui/material/InputBase'
import { useAppSelector, useSearch } from '../../../../hooks'
import { useLocation, useSearchParams } from 'react-router-dom'
import { selectAccessToken } from '../../../../store/reducers/selectors'

const SearchIconWrapper = styled('div')(({ theme }) => ({
	color: theme.palette.common.black,
	padding: theme.spacing(0, 2),
	height: '100%',
	position: 'static',
	pointerEvents: 'none',
	display: 'flex',
	alignItems: 'center',
	justifyContent: 'center',
}))
const StyledSearch = styled('div')(({ theme }) => ({
	width: '400px',
	height: '24px',
	background: 'rgb(255, 255, 255)',
	borderRadius: '24px',
	display: 'flex',
	flexDirection: 'row',
	alignItems: 'center',
	padding: '12px 20px 12px 20px',
	margin: '0px 80px',
	'&:hover': {
		backgroundColor: alpha(theme.palette.common.black, 0.25),
	},
}))

const StyledInputBase = styled(InputBase)(({ theme }) => ({
	color: theme.palette.common.black,
	width: '400px',
	'& .MuiInputBase-input': {
		padding: theme.spacing(1, 1, 1, 0),
		paddingLeft: `calc(1em + ${theme.spacing(4)})`,
		transition: theme.transitions.create('width'),
		[theme.breakpoints.up('sm')]: {
			width: '12ch',
			'&:focus': {
				width: '20ch',
			},
		},
	},
}))

const Search = () => {
	const accessToken = useAppSelector(selectAccessToken)
	const [searchParams] = useSearchParams()
	const location = useLocation()
	const initialSearchParam = searchParams.get('search')
	const [searchInput, setSearchInput] = useState(initialSearchParam)
	useSearch({ searchInput: searchInput })

	return (
		<>
			{location.pathname === '/catalog' && accessToken && (
				<StyledSearch>
					<SearchIconWrapper>
						<SearchIcon />
					</SearchIconWrapper>
					<StyledInputBase
						placeholder='Поиск'
						value={searchInput || ''}
						onChange={(event: ChangeEvent<HTMLInputElement>) =>
							setSearchInput(event.target.value)
						}
					/>
				</StyledSearch>
			)}
		</>
	)
}

export default Search
